package com.nullpointer.xchat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.nullpointer.xchat.libs.TouchImageView;
import com.nullpointer.xchat.utils.Common;
import com.nullpointer.xchat.utils.DataManager;

public class ViewImageActivity extends Activity {
	private ImageButton ibBack;
	private ImageButton ibDownload;
	private ProgressBar pbLoading;
	private TouchImageView tvImage;
	private ProgressDialog spinner;
	private String imageURL;
	private final String FOLDER_NAME = "XChat";
	private Bitmap image;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		DataManager.getInstance(this).setIsShowNotify(false);
		setContentView(R.layout.activity_view_image);
		findViewIDs();
		init();
		setEvent();
	}

	private void setEvent() {
		ibBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		ibDownload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveImageToFile();
			}
		});
	}

	private void init() {
		imageURL = getIntent().getStringExtra(Common.ExtraKey.IMAGE_URL);
		spinner = new ProgressDialog(this);
		spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		spinner.setCanceledOnTouchOutside(false);
		spinner.setCancelable(false);
		ibDownload.setEnabled(false);
		if (imageURL == null) {
			return;
		}
		AQuery aq = new AQuery(this);
		aq.id(tvImage).progress(pbLoading)
				.image(imageURL, true, true, 0, 0, new BitmapAjaxCallback() {
					@Override
					public void callback(String url, ImageView iv, Bitmap bm,
							AjaxStatus status) {
						if (bm != null) {
							image = bm;
							tvImage.setImageBitmap(bm);
							pbLoading.setVisibility(View.GONE);
							tvImage.setZoom(1);
							ibDownload.setEnabled(true);
						}
					}
				});
	}

	private void findViewIDs() {
		ibBack = (ImageButton) findViewById(R.id.ib_back);
		ibDownload = (ImageButton) findViewById(R.id.ib_download);
		pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
		tvImage = (TouchImageView) findViewById(R.id.tv_image);

	}

	protected void saveImageToFile() {
		if (image == null) {
			Toast.makeText(this, "Can not save this image!", Toast.LENGTH_LONG)
					.show();
			return;
		}
		new SaveImageTask().execute();
	}

	public void showProgessbar(String text) {
		spinner.setMessage(text);
		spinner.show();
	}

	public void hideProgessbar() {
		if (spinner == null) {
			return;
		}
		spinner.dismiss();
	}

	private class SaveImageTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			showProgessbar("Save image...!");
		}

		@Override
		protected String doInBackground(Void... params) {
			String root = Environment.getExternalStorageDirectory().toString();
			File newDir = new File(root + "/" + FOLDER_NAME);
			newDir.mkdir();
			String photoName = Long.toString(new Date().getTime()) + ".png";
			File file = new File(newDir, photoName);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream out;
			try {
				out = new FileOutputStream(file);
				image.compress(Bitmap.CompressFormat.PNG, 100, out);
				out.flush();
				out.close();
				return file.getAbsolutePath();
			} catch (FileNotFoundException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgessbar();
			if (result != null) {
				Toast.makeText(ViewImageActivity.this,
						"Save image at " + result, Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(ViewImageActivity.this,
						"Can not save this image!", Toast.LENGTH_LONG).show();
			}

		}

	}

}
